package cn.saas.jingtandata;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.widget.CheckBox;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class ChooseD310FileActivity extends AppCompatActivity {


    /**
     * 文件后缀类型
     */
    public static final String FILE_SUFFIC_TXT = ".txt";
    /**
     * 文件后缀类型
     */
    public static final String FILE_SUFFIC_DAT = ".dat";

    /**
     * 文件选择
     */
    public static final int INTENT_REQUEST_FILE_CHOOSE = 10001;
    private static final String TAG = "aaaaa";
    /**
     * 非日期类型
     */
    public static final int FILE_TYPE_NO_DATE = 0;
    /**
     * 包含日期
     */
    public static final int FILE_TYPE_HAS_DATE = 1;

    private boolean isPermission = false;
    private RadioGroup mSamIntervalGroup;
    private RadioGroup mFileTypeGroup;
    private RadioGroup mDeviceTypeGroup;
    /**
     * kml 文件路径
     */
    private String kmlFilePath;
    /**
     * kml文件后缀
     */
    public static final String KML_FILE_EXT = "kml";
    private ProgressDialog mProgressDialog;
    private CheckBox mPrefixCheck;
    /**
     * 操作句柄
     */
    public static final int MAG_IMPORT_ALL_SUCCESS = 1001;
    /**
     * 钻孔导入失败
     */
    public static final int MAG_IMPORT_HOLE_FAIL = 1002;
    /**
     * 钻孔导入成功
     */
    public static final int MAG_IMPORT_HOLE_SUCCESS = 1003;
    /**
     * 等待导入文件列表
     */
    private List<String> mWaitImportFile;
    private CheckBox mUnitConverCheck;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            List<LpCptItemBean> itemBean = (List<LpCptItemBean>) msg.obj;
            switch (msg.what) {
                case MAG_IMPORT_ALL_SUCCESS:
                    if (mProgressDialog != null) {
                        mProgressDialog.dismiss();
                    }
                    Toast.makeText(ChooseD310FileActivity.this, "数据导入完成",
                            Toast.LENGTH_SHORT).show();

                    Intent intent = new Intent(ChooseD310FileActivity.this, HoleCptViewActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("data", (Serializable) itemBean);
                    intent.putExtras(bundle);
                    startActivity(intent);
                    finish();
                    break;
                case MAG_IMPORT_HOLE_FAIL:
                    Toast.makeText(ChooseD310FileActivity.this, msg.obj + "保存失败",
                            Toast.LENGTH_SHORT).show();
                    break;
                case MAG_IMPORT_HOLE_SUCCESS:
                    Intent intent1 = new Intent(ChooseD310FileActivity.this, HoleCptViewActivity.class);
                    Bundle bundle1 = new Bundle();
                    bundle1.putSerializable("data", (Serializable) itemBean);
                    intent1.putExtras(bundle1);
                    startActivity(intent1);
                    finish();
                    break;
                default:
                    break;
            }
        }
    };
    private RadioButton pyCheckBox;


    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_choose_data_file);
        mSamIntervalGroup = (RadioGroup) findViewById(R.id.sam_interval_group);
        mFileTypeGroup = (RadioGroup) findViewById(R.id.file_type_group);
        mDeviceTypeGroup = (RadioGroup) findViewById(R.id.delvice_type_group);
        mPrefixCheck = (CheckBox) findViewById(R.id.file_prefix);
        mUnitConverCheck = (CheckBox) findViewById(R.id.unit_conver);
        pyCheckBox = (RadioButton) findViewById(R.id.device_type_py);

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
            isPermission = true;
        } else {
            requestPermission();
        }

        TextView mTv = (TextView) findViewById(R.id.control_btn);
        mTv.setOnClickListener(v -> {
            if (isPermission) {
                mWaitImportFile = new ArrayList<>();
                // 初始化待导入文件列表
                String fileSuffix = FILE_SUFFIC_TXT;
                switch (mFileTypeGroup.getCheckedRadioButtonId()) {
                    case R.id.file_type_txt:
                        fileSuffix = FILE_SUFFIC_TXT;
                        break;
                    case R.id.file_type_dat:
                    case R.id.file_type_dat_date:
                        fileSuffix = FILE_SUFFIC_DAT;
                        break;
                    default:
                        break;
                }
                startChooseFile(fileSuffix);
            } else {
                requestPermission();
            }
        });

        mProgressDialog = new ProgressDialog(this);
        mProgressDialog.setTitle("loading...");
    }

    /**
     * 选择文件
     *
     * @Title: startChooseFile
     * @Description: TODO(这里用一句话描述这个方法的作用)
     */
    private void startChooseFile(String suffic) {
        Intent intent = new Intent(this, FileBrowseActivity.class);
        intent.putExtra(FileBrowseActivity.INTENT_PARAM_FILE_TYPE,
                FileBrowseActivity.FILTER_TYPE_FILE);
        intent.putExtra(FileBrowseActivity.INTENT_PARAM_FILTER_SUFFIX, suffic);
        startActivityForResult(intent, INTENT_REQUEST_FILE_CHOOSE);
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    private void requestPermission() {
        requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    isPermission = true;
                } else {
                    isPermission = false;
                }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case INTENT_REQUEST_FILE_CHOOSE:
                if (RESULT_OK == resultCode) {

                    String[] fileList = data
                            .getStringArrayExtra(FileBrowseActivity.INTENT_RESULT_FILE);
                    startImport(fileList);
                }
                break;

            default:
                break;
        }
    }

    /**
     * 开始导入
     *
     * @param fileList
     * @Title: startImport
     * @Description: TODO(这里用一句话描述这个方法的作用)
     */
    private void startImport(final String[] fileList) {
        if (mProgressDialog != null) {
            mProgressDialog.show();
        }
        if (fileList != null) {
            for (String string : fileList) {
                Log.e(TAG, "FilePath:" + string);
            }
        }
        new Thread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                initImportFile(fileList);
//                mHandler.sendEmptyMessage(MAG_IMPORT_ALL_SUCCESS);
            }
        }).start();
    }


    /**
     * 获取后缀
     *
     * @param file
     * @return
     * @Title: getFileExtension
     * @Description: TODO(这里用一句话描述这个方法的作用)
     */
    public String getFileExtension(File file) {
        String fileName = file.getName();
        if (fileName.lastIndexOf(".") != -1 && fileName.lastIndexOf(".") != 0) {
            return fileName.substring(fileName.lastIndexOf(".") + 1);
        } else {
            return "";
        }
    }

    /**
     * 初始化导入文件列表
     *
     * @param fileList
     * @Title: initImportFile
     * @Description: TODO(这里用一句话描述这个方法的作用)
     */
    private void initImportFile(String[] fileList) {
        String fileSuffix = FILE_SUFFIC_TXT;
        int cptContentType = 0;
        switch (mFileTypeGroup.getCheckedRadioButtonId()) {
            case R.id.file_type_txt:
                fileSuffix = FILE_SUFFIC_TXT;
                cptContentType = FILE_TYPE_NO_DATE;
                break;
            case R.id.file_type_dat:
                fileSuffix = FILE_SUFFIC_DAT;
                cptContentType = FILE_TYPE_NO_DATE;
                break;
            case R.id.file_type_dat_date:
                fileSuffix = FILE_SUFFIC_DAT;
                cptContentType = FILE_TYPE_HAS_DATE;
                break;
            default:
                break;
        }
        double interval = 0;
        switch (mSamIntervalGroup.getCheckedRadioButtonId()) {
            case R.id.interval_ten:
                interval = 0.1;
                break;
            case R.id.interval_five:
                interval = 0.05;
                break;
            default:
                break;
        }
        int deviceType = FusionUnitType.CptDeviceType.DOUBLE;
        switch (mDeviceTypeGroup.getCheckedRadioButtonId()) {
            case R.id.delvice_type_single:
                deviceType = FusionUnitType.CptDeviceType.SINGLE;
                break;
            case R.id.delvice_type_double:
                deviceType = FusionUnitType.CptDeviceType.DOUBLE;
                break;
            case R.id.delvice_type_more:
                deviceType = FusionUnitType.CptDeviceType.MAOR;
                break;
            default:
                break;
        }

        boolean hasPrefic = mPrefixCheck.isChecked();

        // 整理文件
        if (fileList != null && fileList.length > 0) {
            for (String filePath : fileList) {
                getFileList(new File(filePath), fileSuffix);
            }
        }
        //
        if (mWaitImportFile != null && mWaitImportFile.size() > 0) {
            for (String fileName : mWaitImportFile) {
                saveCptData(fileName, interval, deviceType, hasPrefic,
                        cptContentType == FILE_TYPE_HAS_DATE,
                        mUnitConverCheck.isChecked());
            }
        }
    }

    /**
     * @param file
     * @param suffix
     * @Title: getFileList
     * @Description: TODO(这里用一句话描述这个方法的作用)
     */
    private void getFileList(File file, String suffix) {
        if (file != null && file.exists()) {
            if (file.isDirectory()) {
                File[] files = file.listFiles();
                if (files != null && files.length > 0) {
                    for (File subFile : files) {
                        getFileList(subFile, suffix);
                    }
                }
            } else if (file.isFile()) {
                // 后缀为
                if (file.getName().toUpperCase().endsWith(suffix.toUpperCase())) {
                    mWaitImportFile.add(file.getPath());
                }
            }
        }
    }

    /**
     * 导入数据
     *
     * @param filePath   文件路径
     * @param interval   间隔
     * @param DeviceType 设备类型
     * @param hasPrefic  是否有前缀
     * @param hasDate    是否包含日期
     * @param isCMap     是否需要转换为兆帕
     * @Title: saveCptData
     * @Description: TODO(这里用一句话描述这个方法的作用)
     */
    private void saveCptData(String filePath, double interval, int DeviceType,
                             boolean hasPrefic, boolean hasDate, boolean isCMap) {
        if (!TextUtils.isEmpty(filePath)) {
            File file = new File(filePath);
            if (file.exists()) {
                String fileName = file.getName();
                String holeCode = fileName.substring(0,
                        fileName.lastIndexOf(".")).toUpperCase();
                if (hasPrefic) {
                    if (holeCode.startsWith("SJ")) {
                        holeCode = holeCode.replaceFirst("SJ", "");
                    }
                    if (holeCode.startsWith("DJ")) {
                        holeCode = holeCode.replaceFirst("DJ", "");
                    }
                    if (holeCode.startsWith("KJ")) {
                        holeCode = holeCode.replaceFirst("KJ", "");
                    }
                }
                Log.e(TAG, "saveCptData: " + filePath + "\n interval "
                        + interval + "\n DeviceType " + DeviceType + "\n hasPrefic "
                        + hasPrefic + "\n hasDate " + hasDate + "\n isCMap " + isCMap);
                Log.e(TAG, "saveCptData: holeCode " + holeCode);
                if (pyCheckBox.isChecked()) {
                    analysisAndSavePyData(file, interval, hasDate, DeviceType, isCMap);
                }else {
                    analysisAndSaveData(file, interval, hasDate, DeviceType, isCMap);
                }


               /* String holeGuid = mCptImportManage.checkCptHole(mProjGuid,
                        holeCode);
                // 钻孔编码相同，但钻孔类型不同时，需要在原的钻孔编码基础上加上-1后，新建钻孔
                LpHoleInfoBean hole = mCptImportManage.getHoleByID(holeGuid);
                if (hole != null) {
                    // 钻孔类型不相同
                    if (!FusionUnitType.HoleType.HOLE_TYPE_CPT.equals(hole.getHlTypeName())) {
                        LpHoleInfoBean newHole = new LpHoleInfoBean();
                        newHole.setHlBussID(hole.getHlBussID());
                        newHole.setHlBussType(hole.getHlBussType());
                        newHole.setHlcode(holeCode + "-1");
                        newHole.setHlcreator(getUserCode(""));
                        newHole.setHlcreattime(DateTimeControl.getDateTimeNowD());
                        newHole.setHldesignlat(hole.getHlDesignLat());
                        newHole.setHldesignlon(hole.getHlDesignLon());
                        newHole.setHlcollectlat(hole.getHlCollectLat());
                        newHole.setHlcollectlon(hole.getHlCollectLon());
                        newHole.setHlguid(UUID.randomUUID().toString()
                                .replace("-", ""));
                        newHole.setHlsource(FusionUnitType.SourceFrom.LOCAL_CREAT);
                        newHole.setHlstate(FusionUnitType.HoleState.INIT);
                        newHole.setHltypename(FusionUnitType.HoleType.HOLE_TYPE_CPT);
                        mCptImportManage.addHoleInfo(newHole);
                        holeGuid = newHole.getHlGuid();
                    }
                }*/
                // 钻孔不存在
//                else {
                // 若无相同编号的空，则查找是否有相通编码的他为，若有相通编码的塔位，则监理相对应的静探孔
                  /*  List<LpTowerBean> towers = mCptImportManage.getTowerByCode(
                            mProjGuid, holeCode);
                    if (towers != null && towers.size() > 0) {
                        LpTowerBean tower = towers.get(0);
                        LpHoleInfoBean newHole = new LpHoleInfoBean();
                        newHole.setHlBussID(tower.getTwGuid());
                        newHole.setHlBussType(HoleBussType.TOWER);
                        newHole.setHlcode(holeCode);
                        newHole.setHlcreator(getUserCode(""));
                        newHole.setHlcreattime(DateTimeControl
                                .getDateTimeNowD());
                        newHole.setHldesignlat(tower.getTwLat());
                        newHole.setHldesignlon(tower.getTwLon());
                        newHole.setHlcollectlat(tower.getTwLat());
                        newHole.setHlcollectlon(tower.getTwLon());
                        newHole.setHlguid(UUID.randomUUID().toString()
                                .replace("-", ""));
                        newHole.setHlsource(SourceFrom.LOCAL_CREAT);
                        newHole.setHlstate(HoleState.INIT);
                        newHole.setHltypename(HoleType.HOLE_TYPE_CPT);
                        mCptImportManage.addHoleInfo(newHole);
                        holeGuid = newHole.getHlGuid();
                    }
                }*/
               /* if (!TextUtils.isEmpty(holeGuid)) {
                    if (mCptImportManage.analysisAndSaveData(file, holeGuid,
                            getUserCode(""), interval, DeviceType, hasDate,
                            isCMap)) {
                        Message msg = new Message();
                        msg.obj = holeCode;
                        msg.what = MAG_IMPORT_HOLE_SUCCESS;
                        mHandler.sendMessage(msg);
                    } else {
                        Message msg = new Message();
                        msg.obj = holeCode;
                        msg.what = MAG_IMPORT_HOLE_FAIL;
                        mHandler.sendMessage(msg);
                    }
                }*/
            }
        }
    }

    private void analysisAndSavePyData(File file, double interval, boolean hasDate, int deviceType, boolean isCMap) {
        List<PyBean> beans = readPyFile(file, 1);
        List<LpCptItemBean> saveData = new ArrayList<>();
        for (PyBean bean : beans) {
            LpCptItemBean entity = new LpCptItemBean();
            entity.setCbGuid(UUID.randomUUID().toString().replace("-", ""));
            entity.setCbDepth(bean.getDepth());
            entity.setCbZJZL(bean.getSideWall());
            entity.setCbCBZL(bean.getTip());
            saveData.add(entity);
        }
        Message msg = new Message();
        msg.obj = saveData;
        msg.what = MAG_IMPORT_HOLE_SUCCESS;
        mHandler.sendMessage(msg);
    }

    private void analysisAndSaveData(File file, double interval, boolean hasDate, int deviceType, boolean isCMap) {
        // 读取数据
        List<Double> date = readFile(file, hasDate ? 13 : 0);
        // 解析数据
        List<LpCptItemBean> saveData = null;
        switch (deviceType) {
            case FusionUnitType.CptDeviceType.DOUBLE:
                saveData = analysisDouble(date, interval, isCMap);
                break;
            case FusionUnitType.CptDeviceType.MAOR:
                saveData = analysisMore(date, interval, isCMap);
                break;
            case FusionUnitType.CptDeviceType.SINGLE:
                saveData = analysisSingle(date, interval, isCMap);
                break;
            default:
                break;
        }
        double depth = 0;
        if (date != null) {
            depth = round(date.size() / 2 * interval, 2);
        }
        // 保存数据
        Log.e(TAG, "analysisAndSaveData: " + depth);
        Message msg = new Message();
        msg.obj = saveData;
        msg.what = MAG_IMPORT_HOLE_SUCCESS;
        mHandler.sendMessage(msg);
    }

    /**
     * 提供精确的小数位四舍五入处理。
     *
     * @param v     需要四舍五入的数字
     * @param scale 小数点后保留几位
     * @return 四舍五入后的结果
     */
    public static double round(double v, int scale) {
        if (scale < 0) {
            throw new IllegalArgumentException(
                    "The scale must be a positive integer or zero");
        }
        BigDecimal b = new BigDecimal(Double.toString(v));
        BigDecimal one = new BigDecimal("1");
        return b.divide(one, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
    }

    /**
     * 解析多桥/孔压
     *
     * @param dataList
     * @param interval
     * @param isCMap
     * @return
     * @Title: analysisMore
     * @Description: TODO(这里用一句话描述这个方法的作用)
     */
    public List<LpCptItemBean> analysisMore(List<Double> dataList,
                                            double interval, boolean isCMap) {
        List<LpCptItemBean> rel = new ArrayList<LpCptItemBean>();
        double depth = interval;
        if (dataList != null && dataList.size() % 3 == 0) {
            for (int i = 0; i < dataList.size() / 3; i++) {
                LpCptItemBean entity = new LpCptItemBean();
                entity.setCbGuid(UUID.randomUUID().toString().replace("-", ""));
                entity.setCbDepth(depth);
                entity.setCbZJZL(dataList.get(i * 3));
                if (isCMap) {
                    entity.setCbCBZL(dataList.get(i * 3 + 1) / 1000);
                } else {
                    entity.setCbCBZL(dataList.get(i * 3 + 1));
                }
                entity.setCbKXSYL(dataList.get(i * 3 + 2));
                depth += interval;
                rel.add(entity);
            }
        }
        return rel;
    }


    /**
     * 解析单桥
     *
     * @param dataList
     * @param interval
     * @param isCMap
     * @return
     * @Title: analysisSingle
     * @Description: TODO(这里用一句话描述这个方法的作用)
     */
    public List<LpCptItemBean> analysisSingle(List<Double> dataList,
                                              double interval, boolean isCMap) {
        List<LpCptItemBean> rel = new ArrayList<LpCptItemBean>();
        double depth = interval;
        if (dataList != null && dataList.size() % 2 == 0) {
            for (int i = 0; i < dataList.size(); i++) {
                LpCptItemBean entity = new LpCptItemBean();
                entity.setCbGuid(UUID.randomUUID().toString().replace("-", ""));
                entity.setCbDepth(depth);
                entity.setCbZJZL(dataList.get(i));
                depth += interval;
                rel.add(entity);
            }
        }
        return rel;
    }

    /**
     * 解析双桥
     *
     * @param dataList
     * @param interval
     * @param isCMap
     * @return
     * @Title: analysisDouble
     * @Description: TODO(这里用一句话描述这个方法的作用)
     */
    public List<LpCptItemBean> analysisDouble(List<Double> dataList,
                                              double interval, boolean isCMap) {
        List<LpCptItemBean> rel = new ArrayList<LpCptItemBean>();
        double depth = interval;
        if (dataList != null && dataList.size() % 2 == 0) {
            for (int i = 0; i < dataList.size() / 2; i++) {
                LpCptItemBean entity = new LpCptItemBean();
                entity.setCbGuid(UUID.randomUUID().toString().replace("-", ""));
                entity.setCbDepth(depth);
                entity.setCbZJZL(dataList.get(i * 2));
                if (isCMap) {
                    entity.setCbCBZL(dataList.get(i * 2 + 1) / 1000);
                } else {
                    entity.setCbCBZL(dataList.get(i * 2 + 1));
                }
                depth += interval;
                rel.add(entity);
            }
        }
        return rel;
    }

    /**
     * 获取文件所有行
     *
     * @param file
     * @param startLine
     * @return
     * @Title: readFile
     * @Description: TODO(这里用一句话描述这个方法的作用)
     */
    public List<PyBean> readPyFile(File file, int startLine) {
        List<PyBean> bean = new ArrayList<>();
        try {
            FileReader reader = new FileReader(file);
            BufferedReader br = new BufferedReader(reader);
            String line = null;
            int lineNum = 0;
            while ((line = br.readLine()) != null) {
                if (lineNum >= startLine) {
                    if (!TextUtils.isEmpty(line)) {
                        PyBean pyBean = new PyBean();
                        pyBean.setDepth(getDepth(line));
                        pyBean.setTip(getTip(line));
                        pyBean.setSideWall(getSideWall(line));
                        bean.add(pyBean);
                    }
                }
                lineNum++;
            }
            br.close();
            reader.close();
        } catch (IOException e) {
            Log.e(TAG, e.getMessage(), e);
        }
        return bean;
    }

    /**
     * 获取文件所有行
     *
     * @param file
     * @param startLine
     * @return
     * @Title: readFile
     * @Description: TODO(这里用一句话描述这个方法的作用)
     */
    public List<Double> readFile(File file, int startLine) {
        List<Double> content = new ArrayList<Double>();
        try {
            FileReader reader = new FileReader(file);
            BufferedReader br = new BufferedReader(reader);
            String line = null;
            int lineNum = 0;
            while ((line = br.readLine()) != null) {
                if (lineNum >= startLine) {
                    if (!TextUtils.isEmpty(line)) {
                        content.add(stringToDouble(line));
                    }
                }
                lineNum++;
            }
            br.close();
            reader.close();
        } catch (IOException e) {
            Log.e(TAG, e.getMessage(), e);
        }
        return content;
    }

    private Double getSideWall(String line) {
        double v = 0d;
        try {
            String substring = line.substring(line.lastIndexOf("\t") + 1);
            v = Double.parseDouble(substring);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return v;
    }

    private Double getTip(String line) {
        double v = 0d;
        try {
            String substring = line.substring(line.indexOf("\t") + 1, line.lastIndexOf("\t"));
            v = Double.parseDouble(substring);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        return v;
    }

    private Double getDepth(String line) {
        if (line == null) return 0d;
        double data = 0;
        String str = line.substring(0, line.indexOf("\t") - 1);
        if (str.startsWith(".")) {
            data = Double.parseDouble("0" + str);
        }else {
            data = Double.parseDouble( str);
        }
        return data;
    }

    public static double stringToDouble(String value) {
        return stringToDouble(value, 0);
    }

    public static double stringToDouble(String value, double defultValue) {
        try {
            return Double.valueOf(value);
        } catch (Exception ex) {
            return 0;
        }
    }
}